package com.defysoft.waukids.slide;

import java.util.Calendar;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;

public class Main_Slide_Trip extends BaseActivity implements OnClickListener {

	PublicSharedpreferences psf;
	SharedPreferences.Editor editor;
	public Data_Sharedpreferences.SF_Member member;
	public Data_Sharedpreferences.SF_Class class1;
	public Data_Sharedpreferences.SF_School school;
	private SharedPreferences fieldTrip;
	
	String FK_Cla_Mem_Code,FK_Sch_Mem_Code,Sch_Name,Cla_Name;
	TextView textView[] = new TextView[1];
	ImageView imageView[] = new ImageView[2];
	String push[] = new String[2];	
	Toolbar toolbar;
	
	final int START_GCM = 1;
	final int END_GCM = 2;
	final int SUCCESS_STOP_GCM = 7;
	final int FAIL_STOP_GCM = 8;
	final int SUCCESS_START_GCM = 9;
	final int FAIL_START_GCM = 10;

	AlertDialog.Builder builder;
	AlertDialog alertDialog;
	//현장학습 초기화
	Calendar calendar;
	String date;
	String nowdate;	
	//현장학습 추가 메세지.
	EditText editText;
	String message;
	public Sqlite_Connect sqlite_Connect;
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.main_slide_trip_activity);
		psf = new PublicSharedpreferences(this);
		psf.setClasssp();
		psf.setMembersp();
		psf.setSchoolsp();
		member = psf.getMembersp();
		school = psf.getSchoolsp();
		class1 = psf.getClasssp();
		setStartToolbar();
		setStartData();
		registerReceiver(mToastMessageReceiver, new IntentFilter(
				"com.defysoft.waukids.TOAST_MESSAGE"));
	}

	@Override
	public void setStartData() {
		super.setStartData();
		sqlite_Connect = new Sqlite_Connect(this);
		textView[0] = (TextView)findViewById(R.id.MAIN_SLIDE_TRIP_TV_MESSAGE); //상태정보출력용.
		imageView[0] = (ImageView)findViewById(R.id.MAIN_SLIDE_TRIP_TV_START); //현장학습 시작.
		imageView[1] = (ImageView)findViewById(R.id.MAIN_SLIDE_TRIP_TV_STOP); //현장학습종료.
		editText = (EditText)findViewById(R.id.MAIN_SLIDE_TRIP_ET_MESSAGE); 	 //현장학습 메세지.
		FK_Cla_Mem_Code = member.Class;	//반코드.
		FK_Sch_Mem_Code = member.School; //학원코드.
		Sch_Name = school.Name;					//학원이름.
		Cla_Name = class1.Name;					//학원이름.
		fieldTrip = getSharedPreferences("fieldTrip", MODE_PRIVATE);	//현장학습 시작-종료 저장.
		editor = fieldTrip.edit();

		for (int i = 0; i < imageView.length; i++) {
			imageView[i].setOnClickListener(this);
		}
		setNow();	//현재 알림값으로 초기화.
		//현장학습 초기화
		findViewById(R.id.MAIN_SLIDE_TRIP_BTN_NEW).setOnClickListener(this);	//눌리면 초기화.
		calendar = Calendar.getInstance();	//하루지나면 초기화.
		date = calendar.get(Calendar.YEAR) + "."
				+ (calendar.get(Calendar.MONTH) + 1) + "."
				+ calendar.get(Calendar.DAY_OF_WEEK);
		nowdate = calendar.get(Calendar.YEAR) + "."
				+ (calendar.get(Calendar.MONTH) + 1) + "."
				+ calendar.get(Calendar.DAY_OF_WEEK);
		if (!fieldTrip.getString("date", "0").equals(nowdate)) {
			editor.clear();
			editor.commit();
			setNow();
		}
	}
	
	private void setStartToolbar() {
		toolbar = (Toolbar)findViewById(R.id.MAIN_SLIDE_TRIP_TOOLBAR);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case START_GCM:
					message = editText.getText().toString();
					startGcmThread(1);
					break;
				case END_GCM:
					message = editText.getText().toString();
					startGcmThread(2);
					break;
				}
			}
		});
		firstThread.start();
		startDIal();
	}
	
	/** 야외학습시작GCM보내기 */
	protected void startGcmThread(int mode) {	
		try {
			JSONObject jsonObject;
			if (mode == 1) {	//현장학습시작.
				jsonObject = new JSONObject(publicHttpCallback(HTTP_URL, 
						"code=" + CODE_MAIN_SLIDE_TRIP_GCM
						+ "&FK_Cla_Mem_Code="+FK_Cla_Mem_Code
						+ "&FK_Sch_Mem_Code="+FK_Sch_Mem_Code
						+ "&Sch_Name="+Sch_Name
						+ "&Cla_Name="+Cla_Name
						+ "&mode=start"
						+ "&message="+message));
				if (jsonObject.getBoolean("success")) {
					onNetworkCallback(SUCCESS_START_GCM, "");
				} else {
					onNetworkCallback(FAIL_START_GCM, jsonObject.getString("message"));
				}
			} else {
				jsonObject = new JSONObject(publicHttpCallback(HTTP_URL, 
						"code=" + CODE_MAIN_SLIDE_TRIP_GCM
						+ "&FK_Cla_Mem_Code="+FK_Cla_Mem_Code
						+ "&FK_Sch_Mem_Code="+FK_Sch_Mem_Code
						+ "&Sch_Name="+Sch_Name
						+ "&Cla_Name="+Cla_Name
						+ "&mode=stop"
						+ "&message="+message));
				if (jsonObject.getBoolean("success")) {
					onNetworkCallback(SUCCESS_STOP_GCM, "");
				} else {
					onNetworkCallback(FAIL_STOP_GCM, jsonObject.getString("message"));
				}
			}
			

		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where startGcmThread(int mode)");
		};	
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case SUCCESS_START_GCM:		//현장학습 시작 GCM발송 완료. 여기에서 버튼변경.
			if (firstThread == null) {firstThread.interrupt();}
			endDIal();
			Toast.makeText(this, "메세지 발송을 완료하였습니다.", Toast.LENGTH_SHORT).show();
			textView[0].setText("현장학습 진행중 입니다.");
			imageView[0].setVisibility(View.INVISIBLE);
			imageView[1].setVisibility(View.VISIBLE);
			editText.setText("");
			editor.putString("fieldTrip_start", "1");
			editor.putString("fieldTrip_stop", "0");
			editor.putString("fieldTrip_start_message", message);
			editor.putString("date", date);
			editor.commit();
			message = "";
			break;

		case SUCCESS_STOP_GCM:		//현장학습 종료 GCM발송 완료. 여기서 버튼 변경.
			endDIal();
			if (firstThread == null) {firstThread.interrupt();}
			textView[0].setText("시작하려면 현장학습START를\n클릭하세요.");
			Toast.makeText(this, "메세지 발송을 완료하였습니다.", Toast.LENGTH_SHORT).show();
			imageView[1].setVisibility(View.INVISIBLE);
			imageView[0].setVisibility(View.VISIBLE);
			editText.setText("");
			editor.putString("fieldTrip_start", "0");
			editor.putString("fieldTrip_stop", "1");
			editor.putString("fieldTrip_stop_message", message);
			editor.commit();
			message = "";
			break;
			
		case FAIL_START_GCM:
			if (firstThread == null) {firstThread.interrupt();}
			endDIal();
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();			
			break;
		case FAIL_STOP_GCM:
			if (firstThread == null) {firstThread.interrupt();}
			endDIal();
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();			
			break;
		case CATCH_EXCEPTION:
			if (firstThread == null) {firstThread.interrupt();}
			endDIal();
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"Main_Slide_Trip", member.Email);
			break;
		}
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.MAIN_SLIDE_TRIP_TV_START:
			dialog_Delete(1);
			break;
		case R.id.MAIN_SLIDE_TRIP_TV_STOP:
			dialog_Delete(2);
			break;
		case R.id.MAIN_SLIDE_TRIP_BTN_NEW:
			builder = new AlertDialog.Builder(this);
			builder.setMessage("현장학습을 초기화 하겠습니까?")
			.setCancelable(false)
			.setPositiveButton("네", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					editor.clear();
					editor.commit();
					setNow();
					dialog.cancel();
				}
			})
			.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			alertDialog = builder.create();
			alertDialog.show();
			break;
		}
	}
	/** 현재 알림값으로 초기화 */
	private void setNow() {
		imageView[0].setVisibility(View.VISIBLE);
		imageView[1].setVisibility(View.VISIBLE);
		push[0] = fieldTrip.getString("fieldTrip_start", "0");
		push[1] = fieldTrip.getString("fieldTrip_stop", "0");
			if (push[0].equals("0")) {
				textView[0].setText("시작하려면 현장학습START를\n클릭하세요.");
				imageView[1].setVisibility(View.INVISIBLE);
				editText.setText("");
			} else {
				textView[0].setText("현장학습 진행중 입니다.");
				imageView[0].setVisibility(View.INVISIBLE);
			}
	}
	/** 현장학습 시작.종료 클릭시. */	
	private void dialog_Delete(int i) {
		builder = new AlertDialog.Builder(this);
		if (i==1) {	//현장학습 시작 클릭
			alertDialog("현장학습을 시작 하겠습니까?", START_GCM);
		} else if(i==2){
			alertDialog("현장학습을 종료 하겠습니까?", END_GCM);
		}
	}
	
	/**네. 아니오. 선택 다이얼로그 */	
	void alertDialog(String string_title, int int_code) {
		final String title = string_title;
		final int code = int_code;
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Main_Slide_Trip.this);
		AlertDialog alert;
		builder.setMessage(title)
				.setCancelable(false)
				.setPositiveButton("네", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						startNetwork(code);
					}
				})
				.setNegativeButton("아니오",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
		alert = builder.create();
		alert.show();
	}
	
	private final BroadcastReceiver mToastMessageReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			LinearLayout layout = (LinearLayout)getLayoutInflater().inflate(R.layout.toast_layout, null);
			TextView toast_tv = (TextView)layout.findViewById(R.id.TOAST_LAYOUT_TV);
			Toast toast = new Toast(Main_Slide_Trip.this);
			toast.setView(layout);
			toast_tv.setText(intent.getStringExtra("PUSH_NAME")+" : "+intent.getStringExtra("PUSH_SUB"));
			toast.setDuration(Toast.LENGTH_LONG);
			toast.show();
		}
	};
	
}